import { HubConnection, HubConnectionBuilder, LogLevel } from '@aspnet/signalr';
import { Subject } from 'rxjs';

export class SignalrService {
    private _hubConnection: HubConnection;
    private msgSignalrSource = new Subject();
    msgReceived$ = this.msgSignalrSource.asObservable();

    constructor() {
        this.init()
    }
    /**
     * 断开连接
     */
    public stop() {
        this._hubConnection.stop();
    }
    /**
     * 初始化 
     */
    private init() {
        this.register();
        this.stablishConnection();
        this.registerHandlers();
    }
    /**
     * 创建连接对象
     */
    private register() {
        this._hubConnection = new HubConnectionBuilder()
            .withUrl('/socket/messageHub')
            .configureLogging(LogLevel.Information)
            .build();
    }
    /**
     * 启动连接
     */
    private stablishConnection() {
        this._hubConnection.start()
            .then(() => {
                console.log('Hub已连接！')
            })
            .catch(() => {
                console.log('Hub建立连接出错，3稍后重试！')
                setTimeout(() => this.stablishConnection(), 3000);
            });
        this._hubConnection.onclose(err => {
            console.log("Hub连接已断！");
            this.stablishConnection();
        });
    }
    /**
     * 注册事件处理程序
     */
    private registerHandlers() {
        this._hubConnection.on('ReceiveMessage', (user, message) => {
            this.msgSignalrSource.next({user, message});
        });
    }
}
export default new SignalrService();